package com.example.onlinemusic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.onlinemusic.common.R;
import com.example.onlinemusic.mapper.RankListMapper;
import com.example.onlinemusic.model.domain.RankList;
import com.example.onlinemusic.model.request.RankListRequest;
import com.example.onlinemusic.service.RankListService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RankListServiceImpl extends ServiceImpl<RankListMapper, RankList> implements RankListService {
    @Autowired
    RankListMapper rankListMapper;

    @Override
    public R addRankList(RankListRequest rankListRequest) {
        RankList rankList = new RankList();
        BeanUtils.copyProperties(rankListRequest, rankList);
        if (rankListMapper.insert(rankList) > 0) {
            return R.success("评论成功");
        } else {
            return R.error("评论失败");
        }
    }

    @Override
    public R rankOfSongListId(long songListId) {
        // 1.根据歌单Id查询所有评分列表数据
        // 2.遍历得到评分列表中的分数score，并进行求和
        // 3.计算歌单的平均评分：平均评分=总分/数量
        QueryWrapper<RankList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("song_list_id", songListId);
        List<RankList> rankLists = rankListMapper.selectList(queryWrapper);
        int count = rankLists.size();
        int sum = 0;
        for (RankList item : rankLists) {
            int score = item.getScore();
            sum += score;
        }
        System.out.println("sum=" + sum);
        System.out.println("count=" + count);
        double avg = sum / count;
        return R.success(null, avg);
    }

    @Override
    public R getRankScroe(long consumerId, long songListId) {
        QueryWrapper<RankList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("consumer_id", consumerId);
        queryWrapper.eq("song_list_id", songListId);
        List<RankList> rankLists = rankListMapper.selectList(queryWrapper);
        return R.success(null, rankLists.get(0).getScore());
    }
}
